package com.gxa.saas.interceptor;


import com.gxa.saas.exception.BusinessException;
import com.gxa.saas.exception.ExceptionCode;
import com.gxa.saas.pojo.Log;
import com.gxa.saas.service.LogService;
import com.gxa.saas.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Enumeration;


/**
 * 设计一个拦截器,用于校验前端是否携带token,并对token合法性进行判断
 * beanName:tokenInterceptor
 * @author Administrator
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    LogService logService;
    /**
     * 拦截前的处理操作
     * @param httpServletRequest request对象(header/session)
     * @param httpServletResponse   response对象(转发,通过全局异常处理已经可以实现给前端的异常响应)
     * @param o 封装了一个方法的Method对象: /user/login->login() ->反射得到方法的信息 ->注解
     *          例如:设计一个自定义注解:@NeedToken
     * @return true表示放行,反之表示拦死
     * @throws Exception 把所有的异常都整合为一个,因为有ExceptionController的存在,会被集中处理
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        String requestURI = httpServletRequest.getRequestURI();
        String remoteAddr = httpServletRequest.getRemoteAddr();

        String username = (String) session.getAttribute("username");
        StringBuilder param = new StringBuilder();
        param.append(requestURI);
        param.append(": ");
        Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
        while (parameterNames.hasMoreElements()){

            String s = parameterNames.nextElement();
            param.append(s);
            param.append(":");
            String parameter = httpServletRequest.getParameter(s);
            param.append(parameter);
            param.append("  ");
            System.out.println(s);
        }
        Date date = Date.from(ZonedDateTime.now().toInstant());
        Log log = new Log();
        log.setUsername(username);
        log.setIpAddress(remoteAddr);
        log.setDateline(date);
        log.setRecord(param.toString());
        if (username==null || "".equals(username)){

        }else {
            logService.insert(log);
        }


        //拦截器误拦了资源
        //如果p不是  HandlerMethod 就放行
        if(!(o instanceof HandlerMethod)){
            return true;
        }

//         selectById / update /reg
//        HandlerMethod handlerMethod= (HandlerMethod) o;
//        Method method= handlerMethod.getMethod();
//        NeedToken declaredAnnotation = method.getDeclaredAnnotation(NeedToken.class);
//        //判断方法上有没有需要的注解
//        //如果为true,就表示必须校验token
//        //否则:虽然表示注册/登录,但也不需要校验
//        boolean annotationPresent = method.isAnnotationPresent(NeedToken.class);
//        //然后该方法中存在指定的注解,则判断token
//        if (annotationPresent &&declaredAnnotation.required()){
//            //表示方法存在@NeedToken,就需要在校验token
//
//            //前端通过header
//            String token = httpServletRequest.getHeader("token");
//
//            //服务器中存在的token
//            HttpSession session = httpServletRequest.getSession();
//            Object sysToken = session.getAttribute("token");
//            if (StringUtil.isEmpty(token)){
//                throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
//            }else if (!token.equals(sysToken)){
//                throw new BusinessException(ExceptionCode.WRONG_TOKEN);
//            }
//        }else {
//            //选择直接放行
//            return true;
//        }
//        return true;
//    }
//        String token = httpServletRequest.getHeader("token");
//
//        //服务器中存在的token
//
//        Object sysToken = session.getAttribute("token");
//        if (StringUtil.isEmpty(token)){
//            throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
//        }else if (!token.equals(sysToken)){
//            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
//        }
        return true;
    }
    /**
     * 拦截后放行的处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 拦截后的处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
